#include <stdio.h>
#include "papers.h"
#include "transfer.h"
#include "helper.h"

void papers_create(struct papers_t * papers)
{
  papers->count = 0;
  papers->next_id = 0;
}


int papers_add(struct papers_t * papers, char * author, char * title, char * file_name)
{
  struct paper_t * paper = &papers->papers[papers->count++];
  paper->id = papers->next_id++;
  paper->size = 0;
  paper->complite = 0;
  strncpy(paper->title, title, MAX_TITLE_LENGTH); 
  strncpy(paper->author, author, MAX_TITLE_LENGTH);
  strncpy(paper->file_name, file_name, MAX_FILE_NAME_LENGTH);
  return paper->id;
}

int papers_count(struct papers_t * papers)
{
  return papers->count;
}

struct paper_t * get_paper_by_id(struct papers_t * papers, int id)
{
  int i; 
  for (i = 0; i < papers_count(papers); i++)
    if (papers->papers[i].id == id)
      return &papers->papers[i];
  return 0;
}

void paper_dump(struct paper_t * paper)
{
  printf("%d. %s\t'%s'\n", paper->id, paper->author, paper->title);
}


void papers_dump(struct papers_t * papers) 
{
  int i;
  printf("id author\t\ttitle\n");
  for (i = 0; i < papers->count; i++)
    paper_dump(&papers->papers[i]);
}

void paper_add_block(struct paper_t * paper, char * block, int size)
{
  int new_size = paper->size + size;
  char * new_data = malloc(sizeof(char) * new_size);
  memcpy(new_data, paper->data, paper->size);
  memcpy(new_data + paper->size, block, size);
  free(paper->data);
  paper->data = new_data;
  paper->size = new_size;
}

int paper_get_block(struct paper_t * paper, int block_no, char * block)
{
  int start_byte = block_no * BLOCK_SIZE;
  if (start_byte > paper->size) 
    return -1;
  int block_size = paper->size - start_byte;
  if (block_size > BLOCK_SIZE)
    block_size = BLOCK_SIZE;
  memcpy(block, paper->data + start_byte, block_size);
  return block_size;
}


void paper_dump_data(struct paper_t * paper)
{
  print_buffor(paper->data, paper->size);
}

int papers_get_last_id(struct papers_t * papers)
{
  return papers->count -1;
}

